#!/bin/bash

# Get the last commit message
COMMIT_MSG=$(git log -1 --pretty=%B)
# Extract bug IDs matching pattern #<ID> (e.g., #123, #BUG-456)
BUG_IDS=$(echo "$COMMIT_MSG" | grep -oE '#[0-9A-Za-z_-]+' | sed 's/^#//')

# 在脚本开头添加
exec > /tmp/git-bug-hook.log 2>&1  # 将所有输出重定向到日志文件
echo "=== 新提交触发钩子(V1.0.20251010) ==="
echo "提交信息: $COMMIT_MSG"
echo "提取到的 BUG_IDS: $BUG_IDS"

# Add git-bug's directory to PATH
export PATH="/root/go/bin:$PATH"

# Check if git-bug is installed
if ! command -v git-bug &> /dev/null; then
  echo "Warning: git-bug not found. Skipping bug status update."
  exit 0
fi

# Exit if no bug IDs found
if [ -z "$BUG_IDS" ]; then
  exit 0
else
  echo "Recognize bug: $BUG_IDS"
fi

# Get commit details for the bug comment
COMMIT_HASH=$(git rev-parse HEAD)
COMMIT_SUBJECT=$(git log -1 --pretty=%s)

# Process each bug ID
for BUG_ID in $BUG_IDS; do
  echo "Processing bug ID: $BUG_ID"

  # Validate the bug exists in git-bug
  if ! git-bug bug show "$BUG_ID" &> /dev/null; then
    echo "Warning: Bug ID $BUG_ID not found in git-bug. Skipping."
    continue
  fi

  # 定义关闭触发关键词（空格分隔）
  CLOSE_KEYWORDS="fix close resolve 修复 解决 deal"

  # 检查提交信息是否包含任意关键词（不区分大小写）
  if ! echo "$COMMIT_MSG" | grep -qiE "($(echo $CLOSE_KEYWORDS | tr ' ' '|'))"; then
    # Add a comment linking to the commit
    COMMENT_MSG="comment via commit $COMMIT_HASH:\n$COMMIT_SUBJECT"
    if git-bug bug comment new "$BUG_ID" -m "$COMMENT_MSG"; then
      echo "Added closure comment to bug: $BUG_ID"
    else
      echo "Failed to add comment to bug: $BUG_ID"
    fi
    # not condinue, just loop in for.
    echo "提交信息不含关闭关键词，跳过 git-bug close操作"
    continue
  fi

  # Add a comment linking to the commit
  COMMENT_MSG="Closed via commit $COMMIT_HASH:\n$COMMIT_SUBJECT"
  if git-bug bug comment new "$BUG_ID" -m "$COMMENT_MSG"; then
    echo "Added closure comment to bug: $BUG_ID"
  else
    echo "Failed to add comment to bug: $BUG_ID"
  fi

  # Close the bug
  if git-bug bug status close "$BUG_ID"; then
    echo "Successfully closed bug: $BUG_ID"
  else
    echo "Failed to close bug: $BUG_ID"
    continue
  fi
  
done
